package cn.com.nxt.txb;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import cn.com.nxt.txb.httpdelegate.PushDelegate;
import cn.com.nxt.txb.util.AppConstant;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.util.MqttTraceCallback;

public class MQTTService extends Service implements HttpProtocol, IMqttActionListener, MqttCallback {
    private Boolean myflags = false;
    private String data = "服务器正在执行";
    private static final String TAG = "MQTTService";
    private PushDelegate delegate;
    private byte mqttAddressFlag = 0x006;
    private String mTCPURL;
    private MqttAndroidClient client;

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "服务器已绑定");
        return new MQTTBinder();
    }

    @Override
    public void success(String result, byte flag) {
        //super.success(result, flag);
        try {
            JSONArray array = new JSONArray(result);
            mTCPURL = array.getString(0);
        } catch (Exception e) {
        }
        // Toast.makeText(MQTTService.this, "tcp--" + mTCPURL, Toast.LENGTH_LONG).show();
        connectAction();
    }

    @Override
    public void failure(String result, byte flag, ResponseStatus status) {
        //super.failure(result, flag, status);
        // showToast(result);
    }

    @Override
    public void finished(int flag) {

    }

    @Override
    public void cancelled(int flag) {

    }


    public class MQTTBinder extends android.os.Binder {
        public void setData(String data) {
            MQTTService.this.data = data;
        }

        public MQTTService getService() {
            return MQTTService.this;
        }

        public boolean isClientEmpty() {
            return client == null||!isConnected();
        }
        public boolean isConnected() {
            return client.isConnected();
        }
        /**
         * 订阅
         */
        public void subscribe(String topic) {
            int qos = 2;
            try {
                String[] topics = new String[1];
                topics[0] = topic;
                client.subscribe(topic, qos, null, MQTTService.this);
            } catch (MqttSecurityException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle MqttSecurityException", e);
            } catch (MqttException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle MqttException", e);
            }
        }

        /**
         * 取消订阅
         */
        public void unsubscribe(String topic) {
            int qos = 2;
            try {
                String[] topics = new String[1];
                topics[0] = topic;
                client.unsubscribe(topic);
            } catch (MqttSecurityException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle MqttSecurityException", e);
            } catch (MqttException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle MqttException", e);
            }
        }

        /**
         * 发布
         */
        public void publish(String topic, String message) {
            int qos = 2;
            String[] args = new String[2];
            args[0] = message;
            args[1] = topic + ";qos:" + qos + ";retained:" + false;

            try {
                client.publish(topic, message.getBytes(), qos, false, null, MQTTService.this);
            } catch (MqttSecurityException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to publish a messged from the client with the handle MqttSecurityException", e);
            } catch (MqttException e) {
                Log.e(this.getClass().getCanonicalName(), "Failed to publish a messged from the client with the handle MqttException", e);
            }

        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        delegate = new PushDelegate(this);
        delegate.mqttAddress(AppUtil.mUser.getToken(), mqttAddressFlag);
        myflags = true;
        Log.i(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        data = intent.getStringExtra("data");
        Log.i(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        myflags = false;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    /**
     * Process data from the connect action
     */
    private void connectAction() {
        MqttConnectOptions conOpt = new MqttConnectOptions();
        //mTCPURL="tcp://59.110.173.27:1883";
        client = new MqttAndroidClient(MQTTService.this, mTCPURL, AppUtil.mUser.getPhone());
        conOpt.setCleanSession(false);
        conOpt.setConnectionTimeout(60);
        conOpt.setKeepAliveInterval(200);
//        if (!username.equals(ActivityConstants.empty)) {
//            conOpt.setUserName(username);
//        }
//        if (!password.equals(ActivityConstants.empty)) {
//            conOpt.setPassword(password.toCharArray());
//        }

        boolean doConnect = true;
        // need to make a message since last will is set
        try {
            conOpt.setWill("topic", "message".getBytes(), 2,
                    false);
        } catch (Exception e) {
            Log.e(this.getClass().getCanonicalName(), "Exception Occured", e);
            doConnect = false;
            onFailure(null, e);
        }
        client.setCallback(MQTTService.this);
        //set traceCallback
        client.setTraceCallback(new MqttTraceCallback());
        //connection.addConnectionOptions(conOpt);
        // Connections.getInstance(this).addConnection(connection);
        if (doConnect) {
            try {
                client.connect(conOpt, null, MQTTService.this);
            } catch (MqttException e) {
                Log.e(this.getClass().getCanonicalName(),
                        "MqttException Occured", e);
            }
        }
    }
    //*********************IMqttActionListener   开始**************************

    @Override
    public void onSuccess(IMqttToken iMqttToken) {
        // Toast.makeText(MQTTService.this, "IMqttActionListener onSuccess", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
        // Toast.makeText(MQTTService.this, "IMqttActionListener onFailure", Toast.LENGTH_LONG).show();

    }

    //*********************IMqttActionListener   结束**************************

    //*********************MqttCallback   开始**************************
    @Override
    public void connectionLost(Throwable throwable) {
        if (throwable != null) {
            //Toast.makeText(MQTTService.this, "connectionLost", Toast.LENGTH_LONG).show();
        }
    }

    //
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        JSONObject obj = new JSONObject(mqttMessage.toString());
//        if (s.equals("/meetting/invlite/" + AppUtil.mUser.getPhone())) {//会议邀请
//            meetingInvite(obj);
//        } else if (s.equals("/meetting/invlite/resp/" + AppUtil.mUser.getRommid())) {//会议邀请回复
//            meetingInviteResp(obj);
//        } else
        Log.e("messageArrived","/meetting/handspeak/resp/"+TextureVideoActivity.mRoomID);
        if (s.equals("/meetting/handspeak/apply/" + AppUtil.mUser.getRommid())) {//举手发言
            handspeakApply(obj);
        }else if(s.equals("/meetting/handspeak/cancel/"+TextureVideoActivity.mRoomID)){//取消发言请求
            handspeakCancel(obj,s);
//        }else if(s.equals("/meetting/handspeak/resp/"+TextureVideoActivity.mRoomID)){//举手发言请求后主持人回应
//            handspeakResp(obj, s);
        }else if(s.startsWith("/meetting/handspeak/cancel/")){ //+TextureVideoActivity.mRoomID)){//取消发言请求
            handspeakCancel(obj,s);
        }else if(s.startsWith("/meetting/handspeak/resp/")){ //+TextureVideoActivity.mRoomID)){//举手发言请求后主持人回应
            handspeakResp(obj,s);
        }
//        else if(s.equals("/meetting/in/apply/"+TextureVideoActivity.mRoomID)){//申请参与会议(升级权限）
//            meetingInApply(obj);
//        } else if(s.equals("/meetting/in/cancel/"+TextureVideoActivity.mRoomID)){//取消参与会议的回应（降级权限）
//            meetingInCancel(obj);
//        }else if(s.equals("/meetting/in/resp/"+TextureVideoActivity.mRoomID)){//申请参与会议的回应
//            meetingInResp(obj);
//        }
        Log.i("messageArrived", s + "====" + mqttMessage.toString());
        //  Toast.makeText(MQTTService.this, "messageArrived:----" + s+"===="+mqttMessage.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        //Toast.makeText(MQTTService.this, "IMqttDeliveryToken", Toast.LENGTH_LONG).show();
    }
    //*********************MqttCallback   结束**************************

    //申请参与会议(升级权限）
    private void meetingInApply(JSONObject obj) {
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "upgrade_apply");
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        sendBroadcast(intent);
    }

    //取消参与会议的回应（降级权限）
    private void meetingInCancel(JSONObject obj) {
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "upgrade_cancel");
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        sendBroadcast(intent);
    }

    //申请参与会议的回应
    private void meetingInResp(JSONObject obj) {
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        if(!phone.equals(AppUtil.mUser.getPhone()))
            return;
        int status=obj.optInt("status");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "upgrade_resp");
        intent.putExtra("status", status);
        sendBroadcast(intent);
    }

    //举手发言请求
    private void handspeakApply(JSONObject obj) {
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "hand_apply");
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        sendBroadcast(intent);
    }

    //取消发言
    private void handspeakCancel(JSONObject obj,String tic) {
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "hand_cancel");
        intent.putExtra("name", name);
        intent.putExtra("tic", tic);
        intent.putExtra("phone", phone);
        sendBroadcast(intent);
    }
    //举手发言请求后主持人回应
    private void handspeakResp(JSONObject obj,String tic) {
        Log.e("messageArrived",obj+"--"+tic);
        String name=obj.optString("name");
        String phone=obj.optString("phone");
        if(!phone.equals(AppUtil.mUser.getPhone()))
            return;
        int status=obj.optInt("status");
        //String waitNum=obj.optString("wait_num");
        Intent intent = new Intent(AppConstant.MQTT_AUDIT);
        intent.putExtra("type", "hand_resp");
        intent.putExtra("tic", tic);
        //intent.putExtra("wait_num", waitNum);
        intent.putExtra("status", status);
        sendBroadcast(intent);
    }

    private void meetingInviteResp(JSONObject obj) {//会议邀请回复
        String srcName = obj.optString("src_name");
        String srcPhone = obj.optString("src_phone");
        String dstName = obj.optString("dst_name");
        String dstPhone = obj.optString("dst_phone");
        int status = obj.optInt("status");
    }

    /**
     * "src_name":"", // 呼叫方的名字
     * "src_phone":"", //呼叫方的手机号
     * "dst_name":"", // 被邀请的名字
     * "dst_phone":"", //被邀请的手机号
     * "roomid":"" // 会议室ID
     */
    private void meetingInvite(JSONObject obj) {//会议邀请
        String srcName = obj.optString("src_name");
        String srcPhone = obj.optString("src_phone");
        String dstName = obj.optString("dst_name");
        String dstPhone = obj.optString("dst_phone");
        String roomid = obj.optString("roomid");
        Intent intent = new Intent(MQTTService.this, CallMeetingActivity.class);
        intent.putExtra("username", srcName);
        intent.putExtra("phone", srcPhone);
        intent.putExtra("dst_name", dstName);
        intent.putExtra("dst_phone", dstPhone);
        intent.putExtra("roomid", roomid);
        startActivity(intent);
    }
}
